import { ElMessageBox } from 'element-plus';
// 通过轮询检查是否更新，自动刷新页面
// 上一次获取到的script地址
let lastSrcs: any;
//获取页面所有script标签的src属性
const scriptReg = /\<script.*src=["'](?<src>[^"']+)/gm;
//获取当前页面所有script标签的src属性
async function getScriptSrcs() {
  const html = await fetch('/?_timestamp=' + Date.now()).then((res: any) => res.text());
  scriptReg.lastIndex = 0;
  let result: any[] = [];
  let match: any;
  while ((match = scriptReg.exec(html))) {
    result.push(match.groups.src);
  }
  return result;
}
//
async function needUpdate() {
  const newScripts = await getScriptSrcs();
  if (!lastSrcs) {
    lastSrcs = newScripts;
    return false;
  }
  let result = false;
  if (newScripts.length !== lastSrcs.length) {
    result = true;
  }
  for (let i = 0; i < lastSrcs.length; i++) {
    if (newScripts[i] !== lastSrcs[i]) {
      result = true;
      break;
    }
  }
  lastSrcs = newScripts;
  return result;
}

const DURATION = 1000 * 60 * 1; // 1分钟

// 定时检查
function autoRefresh() {
  setTimeout(async () => {
    try {
      const willUpdate = await needUpdate();
      if (willUpdate) {
        ElMessageBox.confirm('检测到页面有更新，是否刷新页面？', '提示', {
          confirmButtonText: '刷新',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => window.location.reload())
          .catch(() => {}); // 用户取消
      }
    } catch (err) {
      console.warn('轮询检查更新失败，将继续下一轮', err);
    } finally {
      autoRefresh(); // 无论成功或失败都继续轮询
    }
  }, DURATION);
}

autoRefresh();
